package com.itheima.health.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.User;
import com.itheima.health.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RequestMapping("/mobile/login")
@Slf4j
@RestController
public class MobileLoginController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MemberService memberService;


    @PostMapping("/smsLogin")
    public Result login(@RequestBody Map param, HttpServletRequest request) {
        log.info("接收到的用户登录信息 map:{}" + param);
        //获取手机号
        String telephone = param.get("telephone").toString();
        // 录入验证码
        String validateCode = param.get("validateCode").toString();

        //找键 type 就是 MOBILE_SIGNIN

        String redisKey = RedisConst.VALIDATE_CODE_PREFIX + "_MOBILE_SIGNIN_" + telephone;

        // 验证码在redis中 从redis上获取
        String code = redisTemplate.opsForValue().get(redisKey).toString();
        // 键去取值 --  值反序列化 Integer类型反序列化的 所以反序列化回来的值 integer类型
        //  存的时候类型
        // 进行比较
        if(!StringUtils.isEmpty(code) && code.equals(code)){//万一 这个session中没存呢
//        if (code != null && code.equals(validateCode)) {
            // 登录成功了 删除redis 并返回true
            Member member = new Member();
            member.setPhoneNumber(telephone);
            member = memberService.createOrUpdate(member);
            request.getSession().setAttribute("member", member);

            //登录
            log.info("[登录成功]", member.getId());
            // 登录成功
            return new Result(true, MessageConst.LOGIN_SUCCESS);
        } else {
            //验证码输入错误
            return new Result(false, MessageConst.VALIDATECODE_ERROR);
        }
    }
}